package com.geniusk.wss;

import io.netty.channel.Channel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户ID和channel的关联关系处理
 */
@Slf4j
public class UserChannelSession {

	@Getter
	private static final ConcurrentHashMap<Long, List<Channel>> userChannelSession = new ConcurrentHashMap<>();

	/**
	 * 信道用户关系
	 */
	private static final ConcurrentHashMap<String, Long> userChannelRelation = new ConcurrentHashMap<>();

	/**
	 * 建立用户信道关系
	 * @param userId 用户ID
	 * @param channel 信道
	 */
	public static void setChannel(Long userId, Channel channel) {
		List<Channel> channelList = userChannelSession.get(userId);
		if(channelList == null || channelList.isEmpty()){
			channelList = new ArrayList<>();
		}
		channelList.add(channel);
		userChannelSession.put(userId, channelList);
		userChannelRelation.put(channel.id().asLongText(),userId);
	}

	/**
	 * 移除用户信道关系
	 * @param userId 用户ID
	 * @param channelId 信道ID
	 */
	public static void removeChannel(Long userId, String channelId){
		List<Channel> channelList = userChannelSession.get(userId);
		if (channelList == null || channelList.isEmpty()) {
			return;
		}
		channelList.removeIf(channel -> channel.id().asLongText().equals(channelId));
		if(channelList.isEmpty()){
			userChannelSession.remove(userId);
		}else {
			userChannelSession.put(userId, channelList);
		}
		userChannelRelation.remove(channelId);
	}

	/**
	 * 根据用户ID获取信道列表
	 * @param userId 用户ID
	 * @return 信道列表
	 */
	public static List<Channel> getChannelListByUserId(Long userId) {
		return userChannelSession.get(userId);
	}

	/**
	 * 根据信道ID获取对应用户ID
	 * @param channelId 信道ID
	 * @return 用户ID
	 */
	public static Long getIdentityIdByChannelId(String channelId){
		return userChannelRelation.get(channelId);
	}

	/**
	 * 打印用户信道关系
	 */
	public static void output() {
		for (HashMap.Entry<Long, List<Channel>> entry : userChannelSession.entrySet()) {
			for(Channel channel : entry.getValue()){
				log.info("userId:{}, channelId:{}", entry.getKey(), channel.id().asLongText());
			}
		}
	}

}
